package fi.tikesos.validator.jena.builtin;

import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.reasoner.rulesys.RuleContext;
import com.hp.hpl.jena.reasoner.rulesys.Util;
import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;
import com.hp.hpl.jena.util.iterator.ClosableIterator;

public class PropertyCountBuiltin extends BaseBuiltin {
	/**
	 * (non-Javadoc)
	 * 
	 * @see com.hp.hpl.jena.reasoner.rulesys.Builtin#getName()
	 */
	public String getName() {
		return "propertyCount";
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin#bodyCall(com.hp.hpl.jena.graph.Node[],
	 *      int, com.hp.hpl.jena.reasoner.rulesys.RuleContext)
	 */
	public boolean bodyCall(Node[] args, int length, RuleContext context) {
		Node subjectForCount = args[0];
		Node propertyToCount = args[1];

		ClosableIterator<Triple> it = context.getGraph().find(subjectForCount,
				propertyToCount, null);
		long count = 0;
		while (it.hasNext() == true) {
			it.next();
			count++;
		}
		it.close();
		context.getEnv().bind(args[2], Util.makeLongNode(count));

		return true;
	}
}
